﻿using MediatR;
using T.Common.Domain.Common;
using RedDragon.RBAC.API.Application.Common.UserRolePermission;
using RedDragon.Common.Domain.AuthorizeRBAC;
using RedDragon.Common.Infrastructure.Interface;
using RedDragon.RBAC.API.Application.Common.Role;
using RedDragon.RBAC.ErrorCodeEnum;

namespace RedDragon.RBAC.API.Application.Common.Permission
{
    public class SearchPermissionHandler : IRequestHandler<SearchPermissionCommand, Result>
    {
        /// <summary>
        /// 角色表仓储
        /// </summary>
        public readonly IBaseRepository<Permissions> permissionsRepository;
        /// <summary>
        /// 日志
        /// </summary>
        private readonly ILogger<SearchPermissionHandler> logger;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="rolesrepository"></param>
        /// <param name="logger"></param>
        public SearchPermissionHandler(IBaseRepository<Permissions> permissionsRepository, ILogger<SearchPermissionHandler> logger)
        {
            this.permissionsRepository = permissionsRepository;
            this.logger = logger;
        }

        /// <summary>
        /// 无条件获取权限列表
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Result> Handle(SearchPermissionCommand request, CancellationToken cancellationToken)
        {
            var result = new Result() { Code = (int)CommonErrorCode.Search };
            try
            {
                var list = await(await permissionsRepository.GetAll()).ToListAsync();
                if (list != null)
                {
                    result.Data = list;
                    result.Code = (int)CommonErrorCode.Success;
                    result.Msg = "权限列表获取成功";
                }
            }
            catch (Exception ex)
            {
                logger.LogError("权限列表获取异常");
                result.Msg = "权限列表获取异常";
            }
            return result;
        }
    }
}
